package com.qdu.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.qdu.entity.Building;
import com.qdu.entity.Classroom;
import com.qdu.entity.CoursePlan;
import com.qdu.entity.CurrentTerm;
import com.qdu.entity.Grade;
import com.qdu.entity.LessionPlan;
import com.qdu.entity.Structure;
import com.qdu.entity.Student;
import com.qdu.entity.Term;
import com.qdu.entity.Users;
import com.qdu.service.AssessService;
import com.qdu.service.BuildingService;
import com.qdu.service.ClassroomService;
import com.qdu.service.CoursePlanService;
import com.qdu.service.GradeService;
import com.qdu.service.LessionPlanService;
import com.qdu.service.StructureService;
import com.qdu.service.StudentService;
import com.qdu.service.TermService;
import com.qdu.service.UsersService;

@Controller
@RequestMapping("/stu")
public class StudentController {

	@Autowired
	BuildingService buildingService;

	
	@Autowired
	LessionPlanService lessionPlanService;

	@Autowired
	TermService termService;

	@Autowired
	CoursePlanService coursePlanService;

	@Autowired
	AssessService assessService;

	@Autowired
	ClassroomService classroomService;
	
	@Autowired
	GradeService gradeService;
	
	@Autowired
	HttpSession session;
	
	@Autowired
	StructureService structureService;
	
	@Autowired
	StudentService studentService;
	
	@Autowired
	PasswordEncoder pwdEncoder;
	
	@Autowired
	UsersService usersService;
	
	@GetMapping("/CheckLessionPlan")
	public String getLessionPlanByMjid(int mjid, int tyear, Model model) {
		List<Term> biglist = termService.selectTermBytyear(tyear);
		List<Term> smalllist = new ArrayList<>();
		if (biglist.size()<=13) {
			smalllist = biglist.subList(1, biglist.size());
		} else if(biglist.size()<=14){
			smalllist = biglist.subList(1, biglist.size() - 1);
		}else {
			smalllist = biglist.subList(1, biglist.size() - 2);
		}
		
		List<List<LessionPlan>> list_list = new ArrayList<>();
		List<LessionPlan> lesslist = new ArrayList<>();
		for(int i=0; i<smalllist.size();i++) {
			lesslist = lessionPlanService.selectLessionPlanBymjidAndtermId(mjid, smalllist.get(i).getTermId());
			list_list.add(lesslist);
		}
	
		model.addAttribute("termList", smalllist);
		model.addAttribute("list_list", list_list);
		return "Student/CheckLessionPlan";
	}

	@GetMapping("/evaluateTeacher")
	public String toEvaluate(int mjid, int termId, int bid, String srollno, Model model) {
		CurrentTerm currentTerm = (CurrentTerm) session.getAttribute("currentTerm");
		Term term = currentTerm.getTerm();
		if(term.getAssess() == 1) {
			String sid = assessService.getAssessBySrollnoAndTermId(srollno, termId);
			if (srollno.equals(sid)) {
				return "error/Done";
			}
			List<CoursePlan> coursePlanList = new ArrayList<>();
			CoursePlan coursePlan = new CoursePlan();
			List<LessionPlan> lessionPlanList = lessionPlanService.selectLessionPlanBymjidAndtermId(mjid, termId);
			for (LessionPlan lsp : lessionPlanList) {
				coursePlan = coursePlanService.selectCoursePlanByThreeId(bid, lsp.getLpid());
				if (coursePlan != null) {
					coursePlanList.add(coursePlan);
				}
			}
			model.addAttribute("coursePlanList", coursePlanList);
			return "Student/Evaluate";
		}
		else {
			return "Student/Forbidden";
		}
		
	}

	@GetMapping("/submitResult")
	@ResponseBody
	public String submit(int[] grade, String[] tid, String[] cid, int termId, String srollno) {
		int length = tid.length;
		for (int i = 0; i < length; i++) {
			// assess = assessService.getOneAssessByThreeId(tid[i], cid[i], termId);
			// if (assess != null) {
			// assess.setAssessResult(assess.getAssessResult() + grade[i]);
			// assessService.modifyAssess(assess, tid[i], cid[i], termId, srollno);
			// } else {
			assessService.addAssess(tid[i], cid[i], termId, grade[i], srollno);
			// }
		}
		return "hello";
	}

	@GetMapping("/toQueryGrade")
	public String toQueryGrade(Model model) {
		List<Integer> list = termService.selectAllTyear();
		model.addAttribute("yearList", list);
		Student stu = (Student)session.getAttribute("loginStudent");
		CurrentTerm cterm = (CurrentTerm)session.getAttribute("currentTerm");
		int termId = cterm.getTermId();
		List<CoursePlan> coursePlanList = new ArrayList<>();
		List<Grade> gradeList = new ArrayList<>();
		List<LessionPlan> lessionPlanList = lessionPlanService.selectLessionPlanBymjidAndtermId(stu.getBatch().getMajor().getMjid(), termId);
		for (LessionPlan lessionPlan : lessionPlanList) {
			CoursePlan coursePlan = coursePlanService.selectCoursePlanByThreeId(stu.getBatch().getBid(), lessionPlan.getLpid());
			if(coursePlan!=null) {
				coursePlanList.add(coursePlan);
			}
		}
		for(CoursePlan coursePlan : coursePlanList) {
			Grade grade = gradeService.getGradeBySrollnoAndCpid(stu.getSrollno(), coursePlan.getCpid());
			if(grade!=null) {
				gradeList.add(grade);
			}
		}
		model.addAttribute("gradeList", gradeList);
		return "Student/QueryGrade";
	}
	
	@GetMapping("/selectGradeByTermId")
	@ResponseBody
	public List<Grade> selectGradeByTermId(int termId, HttpSession session){
		Student stu = (Student)session.getAttribute("loginStudent");
		List<CoursePlan> coursePlanList = new ArrayList<>();
		List<Grade> gradeList = new ArrayList<>();
		List<LessionPlan> lessionPlanList = lessionPlanService.selectLessionPlanBymjidAndtermId(stu.getBatch().getMajor().getMjid(), termId);
		for (LessionPlan lessionPlan : lessionPlanList) {
			CoursePlan coursePlan = coursePlanService.selectCoursePlanByThreeId(stu.getBatch().getBid(), lessionPlan.getLpid());
			if(coursePlan!=null) {
				coursePlanList.add(coursePlan);
			}
		}
		for(CoursePlan coursePlan : coursePlanList) {
			Grade grade = gradeService.getGradeBySrollnoAndCpid(stu.getSrollno(), coursePlan.getCpid());
			if(grade!=null) {
				gradeList.add(grade);
			}
		}
		return gradeList;
	}
	
	@GetMapping("/selectTermByTyear")
	@ResponseBody
	public List<Term> selectTermByTyear(int tyear) {
		List<Term> list = termService.selectCertainTermBytyear(tyear);
		return list;
	}

	@GetMapping("/toSchedule")
	public String toSchedule(Model model) {
		List<Integer> list = termService.selectAllTyear();
		model.addAttribute("yearList", list);
		List<Building> buildlist = buildingService.selectAllBuilding();
		model.addAttribute("buildlist", buildlist);
		return "Student/Schedule";
	}

	@GetMapping("/getScheduleByBidAndCycle")
	@ResponseBody
	public List<Structure> getScheduleByBidAndCycle(int bid, int termId, int cycle, Model model) {
		List<LessionPlan> lessList = lessionPlanService.selectLessionPlanByTermId(termId);
		List<CoursePlan> coursePlanList = new ArrayList<>();
		for (LessionPlan less : lessList) {
			CoursePlan coursePlan = coursePlanService.selectCoursePlanByThreeId(bid, less.getLpid());
			coursePlanList.add(coursePlan);
		}
		List<Structure> list = new ArrayList<>();
		for (CoursePlan coursePlan : coursePlanList) {
			List<Structure> strucList = structureService.getStructureByCoursePlanAndCycle(coursePlan.getCpid(), cycle);
			for (Structure struct : strucList) {
				list.add(struct);
			}
		}
		return list;
	}

	@GetMapping("/getScheduleByClassrmIdAndCycle")
	@ResponseBody
	public List<Structure> getScheduleByClassrmIdAndCycle(int classrmid, int cycle, Model model) {
		List<Structure> list = structureService.getStructureByClassroomAndCycle(classrmid, cycle);
		return list;
	}
	
	@PostMapping("/studentModifyPassword")
	@ResponseBody
	public boolean modifyPassword(String oldPassword,String newPassword,Model model,HttpSession session){
		System.out.println("ss");
		System.out.println(oldPassword);
		System.out.println(newPassword);
		boolean flag = false;
		String msg = "";
		Student stu = (Student) session.getAttribute("loginStudent");
		Users user = usersService.getOneUserById(stu.getSrollno());
		boolean check = pwdEncoder.matches(oldPassword, user.getUpassword());
		if(check) {
			user.setUpassword(pwdEncoder.encode(newPassword));
			usersService.modifyUser(user, 1);
			flag = true;
		}else {
			flag = false;
		}
		return flag;
	}
	@RequestMapping("/toModifyPassword")
	public String toIndex() {
		return "User/ModifyPassword";
	}
	
	@ResponseBody
	@GetMapping("/getClassrmByBuildid")
	public List<Classroom> getClassrmByBuildid(int buildingId){
		List<Classroom> classrmlist = classroomService.selectAllClassroom();
		List<Classroom> classrmlist2 = new ArrayList<Classroom>();
		for(Classroom c:classrmlist) {
			if(c.getBuilding().getBuildingId()==buildingId) {
				classrmlist2.add(c);
			}
		}
		return classrmlist2;
	}
	
	
	@RequestMapping("/upload2") 
	@ResponseBody 
	public String upload(MultipartFile pfile) throws IllegalStateException, IOException {
		
		String oldName=pfile.getOriginalFilename();
		String newName=UUID.randomUUID().toString().replace("-","")
				       +oldName.substring(oldName.lastIndexOf("."));
		System.out.println("----------------------------------------");
		Student stu = (Student) session.getAttribute("loginStudent");
		stu.setBirthday("2000-01-01");
		stu.setEnrolment("2000-01-01");
		stu.setImg(newName);
		studentService.modifyStudent(stu, stu.getBatch().getBid());
		//如果要获取src/main/resources目录下static/img目录的路径，可使用:
		String realPath=ResourceUtils.getURL("classpath:static/img").getPath();
		
		pfile.transferTo(new File(realPath,newName));
		System.out.println("/"+newName);
		//返回上传的图片的路径，用于在页面上显示图片
		return "/"+newName;
	}
	
}
